<?php

/**
 * 十六进制颜色转rgb
 *	hex2rgb('#efefef')
 * @param	$color	string $s_type  
 * @return	array
 */
function hex2rgb($colour)
{
	if ($colour[0] == '#') {
		$colour = substr($colour, 1);
	} 
	if (strlen($colour) == 6) {
		list($r, $g, $b) = array($colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5]);
	} 
	elseif (strlen($colour) == 3) {
		list($r, $g, $b) = array($colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2]);
	} 
	else {
		return false;
	} 
	$r = hexdec($r);
	$g = hexdec($g);
	$b = hexdec($b);
	return array('red' => $r, 'green' => $g, 'blue' => $b);
} 



function code()
{
	session_start();//开启session
	$randval;
	for($i = 0; $i<4; $i++){
	    //产生A-Z之间的ASCII随机数
	    $randstr = mt_rand(ord('A'), ord('Z'));//ord($str)返回字符的ASCII
	    $randv = mt_rand(0, 10);//包括0和10
	    global $randval;
	    //产生0-9之间的随机数
	    if($randv % 2 == 0){//如果是偶数,连接数字
	        $randval .= mt_rand(0, 9);
	    }else{//否则奇数连接字符,用chr获取
	        $randval .= chr($randstr);//chr()返回相对应于 ascii 所指定的单个字符。 
	    }
	}
	$_SESSION["randval"] = $randval;
	$intheight = 16;//验证码背景图的高
	$intwidth = 40;//验证码背景图的宽,可相应修改
	$img = imagecreatetruecolor($intwidth, $intheight);
	$fontcolor = imagecolorallocate($img, 255, 0, 0);
	$backcolor = imagecolorallocate($img, 255, 255, 255);
	imagefill($img, 0, 0, $backcolor);
	
	//画线
	imageline($img, mt_rand(0,$intwidth/3), mt_rand(0,$intheight/3), mt_rand($intwidth/3,$intwidth), mt_rand($intheight/3,$intheight), $fontcolor);
	imageline($img, mt_rand($intwidth/3, $intwidth), mt_rand(0, $intheight/3), mt_rand(0, $intwidth/3), mt_rand(0, $intheight/3), $fontcolor);
	//添加img里边的文字信息
	imagestring($img, 8, mt_rand(0, $intwidth - strlen($randval) * 10), mt_rand(0, $intheight-12), $randval, $fontcolor);
	imagegif($img);
	imagedestroy($img);
}

// 生成验证码图片
function createImage($chars, $width = 60, $height = 16){
	header('Content-type: image/gif');
	$a = $chars{0};
	$b = $chars{1};
	$c = $chars{2};
	$d = $chars{3};
	$im = imagecreate($width, $height);
	$bg = imagecolorallocate($im, 233, 239, 233);
	$fc = imagecolorallocate($im, mt_rand(0,230), mt_rand(0,230), mt_rand(0,230));
	imagestring($im, mt_rand(2,5), mt_rand(0,5), mt_rand(3,3), $a, $fc);
	imagestring($im, mt_rand(2,5), mt_rand(15,25), mt_rand(3,3), $b, $fc);
	imagestring($im, mt_rand(2,5), mt_rand(30,40), mt_rand(3,3), $c, $fc);
	imagestring($im, mt_rand(2,5), mt_rand(45,50), mt_rand(3,3), $d, $fc);
	imagegif($im);
}